package com.tsfyun.scm.config;

import com.tsfyun.common.base.extension.FilingFieldConstant;
import com.tsfyun.common.base.extension.annotation.InsertFill;
import com.tsfyun.common.base.extension.annotation.UpdateFill;
import com.tsfyun.common.base.security.LoginVO;
import com.tsfyun.common.base.security.SecurityUtil;
import com.tsfyun.common.base.util.ArrayUtil;
import com.tsfyun.common.base.util.StringUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

/**
 * mybatis自动填充字段（暂不支持批量修改）.
 * 仅仅只支持SQL是数据库实体对象的新增或者修改,自定义的SQL需自行赋值（因为需要更改SQL）
 */
@Component
@Intercepts({@Signature(
        type = org.apache.ibatis.executor.Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class})})
public class AutoFilingInterceptor implements Interceptor {

    private Properties properties;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        //获取 SQL 命令
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        //获取参数
        Object parameter = invocation.getArgs()[1];
        //fix bug by rick at 20210916 此处有可能是无参数的会导致NPE
        if(Objects.isNull(parameter)) {
            return invocation.proceed();
        }
        //获取私有成员变量
        Field[] declaredFields = parameter.getClass().getDeclaredFields();
        if (parameter.getClass().getSuperclass() != null) {
            Field[] superField = parameter.getClass().getSuperclass().getDeclaredFields();
            if(Objects.nonNull(superField) && superField.length > 0) {
                declaredFields = ArrayUtil.concatAll(declaredFields,superField);
            }
        }

        // 是否为mybatis plug
        boolean isPlugUpdate = parameter.getClass().getDeclaredFields().length == 1
                && parameter.getClass().getDeclaredFields()[0].getName().equals("serialVersionUID");

        //兼容mybatis plus的update，批量新增不做统一处理，需程序自行赋值
        if (isPlugUpdate) {
            Map<String, Object> updateParam = (Map<String, Object>) parameter;
            //防止param1参数为null fix by rick at 2020-05-21
            if(updateParam.containsKey("param1") && Objects.nonNull(updateParam.get("param1"))) {
                Class<?> updateParamType = updateParam.get("param1").getClass();
                declaredFields = updateParamType.getDeclaredFields();
                if (updateParamType.getSuperclass() != null) {
                    Field[] superField = updateParamType.getSuperclass().getDeclaredFields();
                    if (Objects.nonNull(superField) && superField.length > 0) {
                        declaredFields = ArrayUtil.concatAll(declaredFields, superField);
                    }
                }
            }

            if(updateParam.containsKey("collection") && Objects.nonNull(updateParam.get("collection"))) {
                Object tempCollObj = updateParam.get("collection");
                if(tempCollObj instanceof List) {
                    Class<?> updateParamType = ((List) tempCollObj).get(0).getClass();
                    declaredFields = updateParamType.getDeclaredFields();
                    if (updateParamType.getSuperclass() != null) {
                        Field[] superField = updateParamType.getSuperclass().getDeclaredFields();
                        if (Objects.nonNull(superField) && superField.length > 0) {
                            declaredFields = ArrayUtil.concatAll(declaredFields, superField);
                        }
                    }
                }
            }

        }

        for (int i = 0; i < declaredFields.length;i++) {
            Field field = declaredFields[i];

            //insert
            if (field.getAnnotation(InsertFill.class) != null) {
                if (SqlCommandType.INSERT.equals(sqlCommandType)) {
                    field.setAccessible(true);
                    if (isPlugUpdate) {
                        Map<String, Object> updateParam = (Map<String, Object>) parameter;
                        if(updateParam.containsKey("param1")) {
                            setValue(field, updateParam.get("param1"));
                        }
                        if(updateParam.containsKey("collection") && Objects.nonNull(updateParam.get("collection")) ){
                            Object tempCollObj = updateParam.get("collection");
                            if(tempCollObj instanceof List) {
                                List dataList = (List) tempCollObj;
                                for (int k = 0;k < dataList.size();k++) {
                                    setValue(field, dataList.get(k));
                                }
                            }
                        }
                    } else {
                        setValue(field,parameter);
                    }
                }
            }

            //update
            if (field.getAnnotation(UpdateFill.class) != null) {
                if (SqlCommandType.INSERT.equals(sqlCommandType)
                        || SqlCommandType.UPDATE.equals(sqlCommandType)) {
                    field.setAccessible(true);
                    //兼容mybatis plus的update
                    if (isPlugUpdate) {
                        Map<String, Object> updateParam = (Map<String, Object>) parameter;
                        if(updateParam.containsKey("param1")) {
                            setValue(field, updateParam.get("param1"));
                        }
                        if(updateParam.containsKey("collection") && Objects.nonNull(updateParam.get("collection")) ){
                            Object tempCollObj = updateParam.get("collection");
                            if(tempCollObj instanceof List) {
                                List dataList = (List) tempCollObj;
                                for (int k = 0;k < dataList.size();k++) {
                                    setValue(field, dataList.get(k));
                                }
                            }
                        }
                    } else {
                        setValue(field,parameter);
                    }
                }
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        if (o instanceof org.apache.ibatis.executor.Executor) {
            return Plugin.wrap(o, this);
        }
        return o;
    }

    @Override
    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void setValue(Field field,Object parameter) throws Throwable{
        LoginVO loginVO = SecurityUtil.getCurrent();
        boolean autoSetNow = false;
        boolean autoSetUser = false;
        switch (field.getName()) {
            case FilingFieldConstant.DATE_CREATED:
                autoSetNow = true;
                break;
            case FilingFieldConstant.DATE_UPDATED:
                autoSetNow = true;
                break;
            case FilingFieldConstant.CREATE_BY:
                autoSetUser = true;
                break;
            case FilingFieldConstant.UPDATE_BY:
                autoSetUser = true;
                break;
            default:
                break;
        }
        if(autoSetNow) {
            field.set(parameter,LocalDateTime.now());
        }
        if(autoSetUser && Objects.nonNull(loginVO)) {
            field.set(parameter, StringUtils.null2EmptyWithTrim(loginVO.getPersonId()).concat("/").concat(StringUtils.null2EmptyWithTrim(loginVO.getPersonName())));
        }
    }
}
